package com.authine.cloudpivot.ext.controller.workList;


import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/public/VehicleInfoController")
public class VehicleInfoController extends BaseController {

    @Autowired
    CloudSqlService sqlService;

    /**
     * 获取车辆代码序号
     *
     * @param time 例如：2023-03-01
     * @return
     */
    @RequestMapping("getVehicleCode")
    public String getVehicleCode(@RequestParam String time) {
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.VehicleCodeCounter);
        StringBuilder sql = new StringBuilder("select * from ").append(tableName).append(" where inTime = '").append(time).append("' order by createdTime desc limit 1");
        Map<String, Object> map = sqlService.getMap(sql.toString());
        String id = MapUtils.getString(map, "id");
        Integer count = MapUtils.getInteger(map, "count", 0);
        Integer flag = count + 1;
        String format = String.format("%02d", flag);
        Map<String, Object> data = new HashMap<>();
        if (StringUtils.isNotBlank(id)) {
            data.put("id", id);
            data.put("count", flag);
        } else {
            data.put("inTime", time);
            data.put("count", 1);

        }

        BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.VehicleCodeCounter, data, false);
        model.setSequenceStatus(SequenceStatus.COMPLETED.name());
        getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
        return format;
    }

    /**
     * 车辆信息记录  审批流完成后
     */
    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.VehicleInfo, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.VehicleInfoDetail);


        // 判断是否是助理审批就结束了
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
        String administrativeCode = (String) bizObject.get("administrativeCode");

        String code = "";
        if (!responsibleDeptFNumber.equals(administrativeCode)) {
            code = "Activity16";
        } else {
            code = "Activity5";
        }
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, code);
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                // 判断是否是修改
                String basicId = MapUtils.getString(map, "basicId", "");
                if (StringUtils.isNotBlank(basicId)) {
                    //基础信息表id
                    data.put("id", basicId);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.VehicleInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                finishOrModifiyProcess(data);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    private void finishOrModifiyProcess(Map<String, Object> map) {

//        exec   SyncCarInfo
//        @companyid     nvarchar(100),		----公司FID
        Map<String, Object> company = (Map<String, Object>) map.get("company");
        String companyid = company.get("id").toString();
        String administrativeC = MapUtils.getString(map, "administrativeC", "");
        String vehicleNumber = MapUtils.getString(map, "vehicleNumber", "");
        String content = MapUtils.getString(map, "content", "");
//        Date outWorkTime = (Date) map.get("outWorkTime");
        LocalDateTime outWorkTime = (LocalDateTime) map.get("outWorkTime");
//        String registrationDate =  ObjectUtils.isEmpty(registrationDateTemp) ? "" : registrationDateTemp.toLocalDate().toString();

//        Date inTime = (Date) map.get("inTime");
        LocalDateTime inTime = (LocalDateTime) map.get("inTime");
//        Date outTime = (Date) map.get("outTime");
        LocalDateTime outTime = (LocalDateTime) map.get("outTime");

        Map<String, Object> responsibleDeptFid = (Map<String, Object>) map.get("responsibleDeptFid");
        String manageId = responsibleDeptFid.get("id").toString();
        String columnIfo = MapUtils.getString(map, "columnIfo", "");
        String fuelConsumption = MapUtils.getString(map, "fuelConsumption", "");
        String ACode = MapUtils.getString(map, "ACode", "");
        String BCode = MapUtils.getString(map, "BCode", "");
        String workContent = MapUtils.getString(map, "workContent", "");
        String approval = MapUtils.getString(map, "approval", ""); // 审批人
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncCarInfo '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                companyid, administrativeC, vehicleNumber, content, outWorkTime, inTime, outTime, manageId, columnIfo, fuelConsumption, ACode, BCode, workContent, approval);
        log.info("\n==========准备调用[车辆管理]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[车辆管理]存储过程执行完成");
    }

    /**
     * 车辆记录作废
     *
     * @param bizId
     */
    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.VehicleInfoCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.VehicleInfoDetailCancel);
        // 判断是否是助理审批就结束了
        String responsibleDeptFNumber = (String) bizObject.get("responsibleDeptFNumber");
        String administrativeCode = (String) bizObject.get("administrativeCode");
        String code = "";
        if (!responsibleDeptFNumber.equals(administrativeCode)) {
            code = "Activity16";
        } else {
            code = "Activity5";
        }
        //获取审批人
        String approval = getFileBaseInfoWorkFlowApproval(bizObject, code);
        for (Map<String, Object> map : list) {
            try {
                String bascid = (String) map.get("basicId");
                //判断是否已存在，如果不存在，放弃这条数据，直接跳过此次循环
                if (StringUtils.isBlank(bascid)) {
                    continue;
                }
                //获取数据
                Map<String, Object> data = Utils.fileInfoBaseMap(map, approval);
                data.put("id", bascid);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.VehicleInfoBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                toVoidProcess(map);
            } catch (Exception e) {
                log.info("参数：{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * 车辆信息记录作废存储过程
     */
    private void toVoidProcess(Map<String, Object> map) {
        Map<String, Object> company = (Map<String, Object>) map.get("company");
        String companyid = company.get("id").toString();
        String administrativeC = MapUtils.getString(map, "administrativeC", "");
        String vehicleNumber = MapUtils.getString(map, "vehicleNumber", "");
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].CarInfoDisable '%s','%s','%s'",
                companyid, administrativeC, vehicleNumber);
        log.info("\n==========准备调用[车辆信息记录]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[车辆信息记录]存储过程执行完成");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String finalActivityCode) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }

    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {
        //事项基础表id
        String eventObjectId = (String) data.get("eventObjectId");
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.VehicleInfoBasic);
        StringBuilder sql = new StringBuilder("select id  from ").append(tableName).append(" where id ='").append(eventObjectId).append("'");
        Map<String, Object> map = sqlService.getMap(sql.toString());
        return (String) map.get("id");
    }


}
